/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * WorkScheduleService
 * 工作日程表
 * 修改纪录
 * 2020-10-24 版本：1.0 zhanglongfei 创建。
 *
 * @version 版本：1.0
 * @author 作者：zhanglongfei
 * 创建日期：2020-10-24
 */
package com.topscomm.work.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.topscomm.base.BaseRemindTemplate.AppRemindTemplate;
import com.topscomm.base.BaseSystemConst;
import com.topscomm.base.BaseSystemConst.NoticeTypeEnum;
import com.topscomm.base.BaseSystemConst.ShareTypeEnum;
import com.topscomm.base.BaseSystemConst.SourceFlagEnum;
import com.topscomm.base.pojo.BasePermissionManageEntity;
import com.topscomm.base.pojo.BaseRemindConfigEntity;
import com.topscomm.base.pojo.BaseRemindTaskEntity;
import com.topscomm.base.service.IBaseOperateRecordService;
import com.topscomm.base.service.IBasePermissionManageService;
import com.topscomm.base.service.IBaseRemindConfigService;
import com.topscomm.base.service.IBaseRemindTaskService;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.toa.pojo.ToaPubWorkingCalendarEntity;
import com.topscomm.toa.pojo.ToaWorkingCalendarEntity;
import com.topscomm.toa.service.impl.ToaPubWorkingCalendarService;
import com.topscomm.toa.service.impl.ToaWorkingCalendarService;
import com.topscomm.work.WorkSystemConst.WorkSourceAppEnum;
import com.topscomm.work.WorkSystemConst.WorkSourceTypeEnum;
import com.topscomm.work.pojo.WorkScheduleEntity;
import com.topscomm.work.pojo.WorkTaskEntity;
import com.topscomm.work.service.IWorkScheduleService;
import com.topscomm.work.service.IWorkTaskService;
import com.topscomm.work.service.impl.auto.WorkScheduleServiceAuto;

@Service(value = "workScheduleService")
@Scope(value = "singleton")
public class WorkScheduleService extends WorkScheduleServiceAuto implements IWorkScheduleService {
	@Autowired
	private IWorkTaskService workTaskService;
	@Autowired
	private IBaseRemindConfigService baseRemindConfigService;
	@Autowired
	private IBaseOperateRecordService baseOperateRecordService;
	@Autowired
	private IBasePermissionManageService basePermissionManageService;
	@Autowired
	private IBaseRemindTaskService baseRemindTaskService;
	@Autowired
	private ToaWorkingCalendarService toaWorkingCalendarService;
	@Autowired
	private ToaPubWorkingCalendarService toaPubWorkingCalendarService;
	@Autowired
	private CboUserService cboUserService;
	// 前端传递的selectUser的key值对应关系
	private static Map<String, String> typeList = new HashMap<>();
	static {
		typeList.put("usercodes", ShareTypeEnum.User);
		typeList.put("deptcodes", ShareTypeEnum.Dept);
		typeList.put("teamids", ShareTypeEnum.Team);
		typeList.put("roleids", ShareTypeEnum.Role);
		typeList.put("sharecodes", ShareTypeEnum.Share);
	}

	/**
	 * @description:日历添加日程，顺便保存任务
	 * @param entity
	 * @param taskEntity
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年10月27日下午3:39:15
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public WorkScheduleEntity saveCalendarEntity(Map<String, Object> paraMap) {
		WorkScheduleEntity entity = new WorkScheduleEntity();
		List<Map<String, Object>> remindList = null;
		if (paraMap.containsKey("remindList")) {
			remindList = (List<Map<String, Object>>) paraMap.get("remindList");
		}
		List<BasePermissionManageEntity> userList = processSelectUsers(paraMap);
		entity.convertFromMap(paraMap);
		SessionUserBean userBean = getSessionUserBean();
		if (entity.getId() > 0) {
			// 老数据
			WorkScheduleEntity oldEntity = queryById(String.valueOf(entity.getId()));
			updateEntity(entity);
			if (remindList != null) {
				baseRemindConfigService.batchSaveRemindConfigList(String.valueOf(entity.getId()), WorkSourceTypeEnum.WorkSchedule, remindList);
			}
			if (userList != null) {
				// 比对人是否有变化，有变化重新保存人，并发送消息提醒
				StringBufferProxy permissionSql = new StringBufferProxy();
				permissionSql.appendLineSingle("sourcetype='{0}' and sourceid='{1}'", WorkSourceTypeEnum.WorkSchedule, entity.getId());
				List<BasePermissionManageEntity> oldUserList = basePermissionManageService
						.queryByWhere(permissionSql.toString());
				boolean haveChange = comparePermissionManage(oldUserList, userList);
				if (haveChange) {
					basePermissionManageService.batchSaveList(String.valueOf(entity.getId()), WorkSourceTypeEnum.WorkSchedule, userList);
				}
				// 判断地点是否改变
				String oldPlace = oldEntity.getPlace() == null ? "" : oldEntity.getPlace();
				String newPlace = entity.getPlace() == null ? "" : entity.getPlace();
				boolean updateFlag = !oldPlace.equals(newPlace) ||  oldEntity.getBegintime().compareTo(entity.getBegintime()) != 0 ;
				// donghang修改
				pushRemindTask(entity, userList, oldUserList, updateFlag, false, userBean);
			}
			return entity;
		} else if (WorkSourceTypeEnum.WorkTask.equals(entity.getSourcetype())) {
			// 如果是周期任务，那么存储到周期表，由周期表去产生Schedule表的数据
			entity.setSourceapp(WorkSourceAppEnum.Work);
			WorkTaskEntity taskEntity = workTaskService.saveWorkTask(paraMap, remindList, userList);
			entity.setSourceid(String.valueOf(taskEntity.getId()));
		} else {
			entity = insert(entity);
			if (remindList != null) {
				baseRemindConfigService.batchSaveRemindConfigList(String.valueOf(entity.getId()), WorkSourceTypeEnum.WorkSchedule, remindList);
			}
			if (userList != null) {
				basePermissionManageService.batchSaveList(String.valueOf(entity.getId()), WorkSourceTypeEnum.WorkSchedule, userList);
			}
			pushRemindTask(entity, userList, null, false, false, userBean);
		}
		return entity;
	}

	/**
	 * @param subject
	 * @param content
	 * @param sourceId
	 * @param user
	 * @param action
	 * @return
	 * @description:创建日程改动消息
	 * @author: zhanglongfei
	 * @date: 2020年11月12日下午2:39:21
	 * @modify:
	 */
	private BaseRemindTaskEntity createRemindTaskEntity(String subject, String content, String sourceId, Map<String, Object> user, String action) {
		BaseRemindTaskEntity remindTaskEntity = new BaseRemindTaskEntity();
		remindTaskEntity.setContent(content);
		remindTaskEntity.setCreateon(new Date());
		remindTaskEntity.setModifiedon(remindTaskEntity.getCreateon());
		remindTaskEntity.setNoticetype(NoticeTypeEnum.App);
		remindTaskEntity.setRemindtime(remindTaskEntity.getCreateon());
		remindTaskEntity.setSourceaction(action);
		remindTaskEntity.setSourceid(sourceId);
		remindTaskEntity.setSourcetype(WorkSourceTypeEnum.WorkSchedule);
		remindTaskEntity.setFormid(sourceId);
		remindTaskEntity.setFormtype(WorkSourceTypeEnum.WorkSchedule);
		remindTaskEntity.setState(0);
		remindTaskEntity.setSubject(subject);
		remindTaskEntity.setUsercode(user.get("code").toString());
		remindTaskEntity.setUserid(ConvertUtil.convertToLong(user.get("id")));
		remindTaskEntity.setUsername(user.get("name").toString());
		return remindTaskEntity;
	}

	/**
	 * @description:单纯修改日期信息
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年10月29日下午5:33:53
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void changeCalendarTime(Map<String, Object> paraMap) throws Exception {
		WorkScheduleEntity entity = queryById(paraMap.get("id").toString());
		WorkScheduleEntity oldEntity = (WorkScheduleEntity) entity.deepClone();
		Date beginDate = ConvertUtil.convertToDate(paraMap.get("begintime"));
		boolean isChangeTime = entity.getBegintime().compareTo(beginDate) != 0;
		entity.setBegintime(ConvertUtil.convertToDate(paraMap.get("begintime")));
		entity.setEndtime(ConvertUtil.convertToDate(paraMap.get("endtime")));
		updateEntity(entity);
		// 更新Remind表是因为表里有提前多长时间提醒，开始时间发生变化，应该更新
		// 人员是为了发送更改提醒
		if (isChangeTime) {
			StringBufferProxy sqlBufferProxy = new StringBufferProxy();
			sqlBufferProxy.appendLineSingle("sourcetype='{0}' and sourceid='{1}'", WorkSourceTypeEnum.WorkSchedule, entity.getId());
			this.dao.updateExecute("update " + BaseRemindConfigEntity.tableName + " set modifiedon="
					+ SQLAdapter.getDate() + " where " + sqlBufferProxy.toString());
			List<BasePermissionManageEntity> list = basePermissionManageService.queryByWhere(sqlBufferProxy.toString());
			pushRemindTask(oldEntity, list, list, true, false, getSessionUserBean());
		}
	}

	@Override
	protected void deleteBefore(String whereSql) {
		StringBufferProxy sqlBufferProxy = new StringBufferProxy();
		sqlBufferProxy.appendLineSingle(whereSql.replace(" id ", " sourceid ").replaceAll("\\(", "('")
				.replaceAll("\\)", "')").replaceAll("\\,", "','"));
		sqlBufferProxy.appendLineSingle(" and sourcetype='{0}'", WorkSourceTypeEnum.WorkSchedule);
		baseRemindConfigService.deleteByWhere(sqlBufferProxy.toString());
		baseOperateRecordService.deleteByWhere(sqlBufferProxy.toString());
		basePermissionManageService.deleteByWhere(sqlBufferProxy.toString());
	}

	/**
	 * @description:整理前台传过来的用户数据
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月2日下午4:38:49
	 * @modify:
	 */
	@Override
	public List<BasePermissionManageEntity> processSelectUsers(Map<String, Object> paraMap) {
		if (!paraMap.containsKey("selectUsers")) {
			return null;
		}
		Map<String, Object> users = (Map<String, Object>) paraMap.get("selectUsers");
		List<BasePermissionManageEntity> list = new ArrayList<>();
		for (String key : typeList.keySet()) {
			if (users.containsKey(key)) {
				String userCode = ConvertUtil.convertToString(users.get(key));
				if (userCode.length() > 0) {
					BasePermissionManageEntity entity = new BasePermissionManageEntity();
					entity.setShareobjects(userCode);
					entity.setShareobjectsdesc(ConvertUtil
							.convertToString(users.get(key.replace("codes", "").replace("ids", "") + "names")));
					entity.setSharetype(typeList.get(key));
					entity.setSourceflag(SourceFlagEnum.Owner);
					entity.setCreateon(new Date());
					entity.setModifiedon(entity.getCreateon());
					entity.setSourceusercodes(ConvertUtil.convertToString(paraMap.get(WorkScheduleEntity.FieldHandleusercode)));
					entity.setSourceusernames(ConvertUtil.convertToString(paraMap.get(WorkScheduleEntity.FieldHandleusername)));
					list.add(entity);
				}
			}
		}
		return list;
	}

	/**
	 * @description:将BasePermissionManage表的list转前台Map格式
	 * @param list
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月12日下午1:57:50
	 * @modify:
	 */
	private Map<String, Object> processToMapUsers(List<BasePermissionManageEntity> list) {
		Map<String, Object> result = new HashMap<>();
		for (BasePermissionManageEntity basePermissionManageEntity : list) {
			if (ShareTypeEnum.Dept.equals(basePermissionManageEntity.getSharetype())) {
				result.put("deptcodes", basePermissionManageEntity.getShareobjects());
				result.put("deptnames", basePermissionManageEntity.getShareobjectsdesc());
			} else if (ShareTypeEnum.User.equals(basePermissionManageEntity.getSharetype())) {
				result.put("usercodes", basePermissionManageEntity.getShareobjects());
				result.put("usernames", basePermissionManageEntity.getShareobjectsdesc());
			} else if (ShareTypeEnum.Role.equals(basePermissionManageEntity.getSharetype())) {
				result.put("roleids", basePermissionManageEntity.getShareobjects());
				result.put("rolenames", basePermissionManageEntity.getShareobjectsdesc());
			} else if (ShareTypeEnum.Team.equals(basePermissionManageEntity.getSharetype())) {
				result.put("teamids", basePermissionManageEntity.getShareobjects());
				result.put("teamnames", basePermissionManageEntity.getShareobjectsdesc());
			} else if (ShareTypeEnum.Share.equals(basePermissionManageEntity.getSharetype())) {
				result.put("sharecodes", basePermissionManageEntity.getShareobjects());
				result.put("sharenames", basePermissionManageEntity.getShareobjectsdesc());
			}
		}
		return result;
	}

	/**
	 * @description:批量添加，对外接口
	 * @param list
	 * @param isSendMessage
	 * @author: zhanglongfei
	 * @date: 2020年11月27日下午5:57:47
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void mulitSubmitWorkSchedule(List<Map<String, Object>> list, boolean isSendMessage) {
		for (Map<String, Object> map : list) {
			WorkScheduleEntity workScheduleEntity = new WorkScheduleEntity();
			workScheduleEntity.convertFromMap(map);
			List<Map<String, Object>> remindMapList = null;
			List<BaseRemindConfigEntity> remindList = new ArrayList<>();
			if (map.containsKey("remindList")) {
				remindMapList = (List<Map<String, Object>>) map.get("remindList");
			}
			if (remindMapList != null) {
				for (Map<String, Object> remindMap : remindMapList) {
					BaseRemindConfigEntity remindConfigEntity = new BaseRemindConfigEntity();
					remindConfigEntity.convertFromMap(remindMap);
					remindList.add(remindConfigEntity);
				}
			}
			List<BasePermissionManageEntity> userList = processSelectUsers(map);
			submitWorkSchedule(workScheduleEntity, userList, remindList, isSendMessage, false);
		}
	}

	/**
	 * 工作日程，统一进行修改、添加、删除操作
	 *
	 * @description:
	 * @param workScheduleEntity
	 * @param personEntityList
	 * @param remindList
	 * @author: donghang
	 * @date: 2020年11月5日下午4:16:12
	 * @modify:
	 */
	@Override
	public void submitWorkSchedule(WorkScheduleEntity workScheduleEntity, List<BasePermissionManageEntity> personEntityList, List<BaseRemindConfigEntity> remindList, boolean isSendMessage, boolean isFirstPublish) {
		if (ConvertUtil.convertToString(workScheduleEntity.getSourcetype()).length() == 0
				&& ConvertUtil.convertToString(workScheduleEntity.getSourceid()).length() == 0) {
			throw new ServiceException("参数不全");
		}
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		sql.appendSingle(" and sourceapp = '{0}' and sourcetype='{1}' and sourceid='{2}'", workScheduleEntity.getSourceapp(), workScheduleEntity.getSourcetype(), workScheduleEntity.getSourceid());
		List<WorkScheduleEntity> oldWorkList = this.queryByWhere(sql.toString());
		if (oldWorkList.size() > 1) {
			throw new ServiceException("传递数据错误");
		}
		if (oldWorkList.size() == 0) {// 日程表新增
			workScheduleEntity = this.insert(workScheduleEntity);
			// 基础权限
			for (BasicEntity basicEntity : personEntityList) {
				BasePermissionManageEntity basePermissionManageEntity = (BasePermissionManageEntity) basicEntity;
				basePermissionManageEntity.setSourceid(ConvertUtil.convertToString(workScheduleEntity.getId()));
				basePermissionManageEntity.setSourcetype(WorkSourceTypeEnum.WorkSchedule);
				basePermissionManageEntity.setSourceflag(SourceFlagEnum.Owner);
				basePermissionManageEntity.setCreateon(new Date());
				basePermissionManageEntity.setModifiedon(basePermissionManageEntity.getCreateon());
			}
			List<BasicEntity> tempPermissionList = new ArrayList<>();
			tempPermissionList.addAll(personEntityList);
			this.basePermissionManageService.insertBatch(tempPermissionList);
			// 提醒
			List<BasicEntity> tempRemindList = new ArrayList<>();
			tempRemindList.addAll(remindList);
			for (BasicEntity basicEntity : remindList) {
				BaseRemindConfigEntity baseRemindConfigEntity = (BaseRemindConfigEntity) basicEntity;
				baseRemindConfigEntity.setSourceid(ConvertUtil.convertToString(workScheduleEntity.getId()));
				baseRemindConfigEntity.setSourcetype(WorkSourceTypeEnum.WorkSchedule);
				baseRemindConfigEntity.setState(0);
				baseRemindConfigEntity.setCreateon(new Date());
				baseRemindConfigEntity.setModifiedon(baseRemindConfigEntity.getCreateon());
			}
			this.baseRemindConfigService.insertBatch(tempRemindList);
			Date currentDate = new Date();
			// 需要发送，并且时间没有过时
			if (isSendMessage && currentDate.getTime() < workScheduleEntity.getBegintime().getTime()) {
				pushRemindTask(workScheduleEntity, personEntityList, null, false, false, null);
			}
		} else {// 其他数据都走变更，注意周期日程
			WorkScheduleEntity oldWorkEntity = oldWorkList.get(0);
			workScheduleEntity.setId(oldWorkEntity.getId());
			this.updateEntity(workScheduleEntity);
			// 权限管理表处理,查看历史数据
			StringBufferProxy permissionSql = new StringBufferProxy();
			permissionSql.appendLineSingle("sourcetype='{0}' and sourceid='{1}'", WorkSourceTypeEnum.WorkSchedule, oldWorkEntity.getId());
			List<BasePermissionManageEntity> oldUserList = basePermissionManageService
					.queryByWhere(permissionSql.toString());
			sql.clear();
			sql.appendSingle(" 1=1 ");
			sql.appendSingle(" and sourcetype='{0}' and sourceid='{1}'", WorkSourceTypeEnum.WorkSchedule, workScheduleEntity.getId());
			this.basePermissionManageService.deleteByWhere(sql.toString());
			for (BasicEntity basicEntity : personEntityList) {
				BasePermissionManageEntity basePermissionManageEntity = (BasePermissionManageEntity) basicEntity;
				basePermissionManageEntity.setSourceid(ConvertUtil.convertToString(workScheduleEntity.getId()));
				basePermissionManageEntity.setSourcetype(WorkSourceTypeEnum.WorkSchedule);
				basePermissionManageEntity.setSourceflag(SourceFlagEnum.Owner);
				basePermissionManageEntity.setCreateon(new Date());
				basePermissionManageEntity.setModifiedon(basePermissionManageEntity.getCreateon());
			}
			List<BasicEntity> tempPermissionList = new ArrayList<>();
			tempPermissionList.addAll(personEntityList);
			this.basePermissionManageService.insertBatch(tempPermissionList);
			// 提醒配置表
			this.baseRemindConfigService.deleteByWhere(sql.toString());
			for (BasicEntity basicEntity : remindList) {
				BaseRemindConfigEntity baseRemindConfigEntity = (BaseRemindConfigEntity) basicEntity;
				baseRemindConfigEntity.setSourceid(ConvertUtil.convertToString(workScheduleEntity.getId()));
				baseRemindConfigEntity.setSourcetype(WorkSourceTypeEnum.WorkSchedule);
				baseRemindConfigEntity.setCreateon(new Date());
				baseRemindConfigEntity.setState(0);
				baseRemindConfigEntity.setModifiedon(baseRemindConfigEntity.getCreateon());
			}
			List<BasicEntity> tempRemindList = new ArrayList<>();
			tempRemindList.addAll(remindList);
			this.baseRemindConfigService.insertBatch(tempRemindList);
			// 比对人是否有变化，有变化发送消息提醒
			// boolean haveChange = comparePermissionManage(oldUserList,
			// personEntityList);
			Date currentDate = new Date();
			if (isSendMessage && currentDate.getTime() < workScheduleEntity.getBegintime().getTime()) {
				if (isFirstPublish == false) {
					pushRemindTask(workScheduleEntity, personEntityList, oldUserList, oldWorkEntity.getBegintime().compareTo(workScheduleEntity.getBegintime()) != 0, false, null);
				} else {// 第一次发布，发送新增消息提醒
					pushRemindTask(workScheduleEntity, personEntityList, null, oldWorkEntity.getBegintime().compareTo(workScheduleEntity.getBegintime()) != 0, false, null);
				}
			}
		}
	}

	/**
	 * 撤销日程
	 *
	 * @description:
	 * @param sourceapp
	 * @param soutcetype
	 * @param sourceid
	 * @author: donghang
	 * @date: 2020年11月5日下午10:04:28
	 * @modify:
	 */
	@Override
	public void cancelWorkSchedule(String sourceapp, String sourcetype, String sourceids) {
		String sourceSql = "";
		String[] strIds = sourceids.split(",");
		for (String sourceId : strIds) {
			sourceSql += "'" + sourceId + "'" + ",";
		}
		if (sourceSql.length() > 0) {
			sourceSql = sourceSql.substring(0, sourceSql.length() - 1);
		}
		StringBufferProxy workSql = new StringBufferProxy();
		workSql.appendSingle(" 1=1 ");
		workSql.appendSingle(" and sourceapp = '{0}' and sourcetype='{1}' and sourceid in ({2})", sourceapp, sourcetype, sourceSql);
		// 删除提醒配置表
		StringBufferProxy remindSql = new StringBufferProxy();
		remindSql.appendSingle(" 1=1 ");
		remindSql.appendSingle(" and sourcetype='{0}' and sourceid in (select id from workschedule where {1})", WorkSourceTypeEnum.WorkSchedule, workSql.toString());
		List<WorkScheduleEntity> scheduleList = this.queryByWhere(workSql.toString());
		List<BasePermissionManageEntity> permissionManageList = basePermissionManageService
				.queryByWhere(remindSql.toString());
		this.baseRemindConfigService.deleteByWhere(remindSql.toString());
		// 删除人员配置表
		this.basePermissionManageService.deleteByWhere(remindSql.toString());
		// 删除日程
		this.deleteExecute("delete from workschedule where " + workSql.toString());
		// 发送提醒
		if (scheduleList.size() == 1) {
			pushRemindTask(scheduleList.get(0), permissionManageList, null, false, true, null);
		}
	}

	/**
	 * @description:日程修改后，通知用户 当前规则：若给他人新增日程，则发送消息提醒
	 * 若修改日程，并且日程的开始时间发生变化，则给日程接收人发送修改通知
	 * 若从日程中取消人，则给日程接收人发送撤销通知
	 * @param scheduleEntity
	 * @param newUserList
	 * @param oldUserList
	 * @param isPushEdit是否要推送编辑用户的信息
	 * @param isDel是否是删除了此条日程
	 * @author: zhanglongfei
	 * @date: 2020年11月12日下午3:12:40
	 * @modify:
	 */
	@Override
	public void pushRemindTask(WorkScheduleEntity scheduleEntity, List<BasePermissionManageEntity> newUserList, List<BasePermissionManageEntity> oldUserList, boolean isPushEdit, boolean isDel, SessionUserBean userBean) {
		cn.hutool.core.thread.ThreadUtil.execAsync(() -> {
			try {
				execPushRemindTask(scheduleEntity, newUserList, oldUserList, isPushEdit, isDel, userBean);
			} catch (Exception e) {
				System.out.println("发送消息出错");
				e.printStackTrace();
				System.out.println(e.getMessage());
			}
		});
	}

	/**
	 * @description:日程修改后，通知用户
	 * @param scheduleEntity
	 * @param newUserList
	 * @param oldUserList
	 * @param isPushEdit
	 * @author: zhanglongfei
	 * @date: 2020年11月12日下午3:12:40
	 * @modify:
	 */
	private void execPushRemindTask(WorkScheduleEntity scheduleEntity, List<BasePermissionManageEntity> newUserList, List<BasePermissionManageEntity> oldUserList, boolean isPushEdit, boolean isDel, SessionUserBean userBean) {
		if (newUserList == null || newUserList.size() == 0) {
			return;
		}
		String from = "", userCode = "";
		if (userBean != null) {
			userCode = userBean.getUser().getCode();
			from = userBean.getDept().getFullname() + "\\" + userBean.getUser().getName();
		} else {
			from = scheduleEntity.getHandleusername();
		}
		List<BasicEntity> pushList = new ArrayList<>();
		// String from = userBean.getDept().getFullname() + "\\" + userBean.getUser().getName();
		String place = scheduleEntity.getPlace();
		boolean placeEmptyFlag = StringUtil.isEmpty(place);
		if (isDel) {
			Map<String, Object> newUserMap = processToMapUsers(newUserList);
			List<Map<String, Object>> newMapList = basePermissionManageService.getAllAttendUser(newUserMap);
			for (Map<String, Object> map : newMapList) {
				if (userCode.equals(ConvertUtil.convertToString(map.get("code")))) {
					continue;
				}
				String content = "";
				if (placeEmptyFlag) {
					content = String.format(AppRemindTemplate.DelContentTemplate1, getDateStringWithWeek(scheduleEntity.getBegintime()), scheduleEntity.getName(), from);
				} else {
					content = String.format(AppRemindTemplate.DelContentTemplate2, getDateStringWithWeek(scheduleEntity.getBegintime()), scheduleEntity.getName(), place, from);
				}
				pushList.add(createRemindTaskEntity(AppRemindTemplate.DelSubjectTemplate, content, String.valueOf(scheduleEntity.getId()), map, BaseSystemConst.BaseActionType.Delete));
			}
		} else if (oldUserList == null) {
			// 新增情况下，若不是给自己添加的，则发送消息
			if (newUserList.size() == 1 && userCode.equals(newUserList.get(0).getShareobjects())) {
				return;
			}
			Map<String, Object> newUserMap = processToMapUsers(newUserList);
			List<Map<String, Object>> newMapList = basePermissionManageService.getAllAttendUser(newUserMap);
			for (Map<String, Object> map : newMapList) {
				if (userCode.equals(ConvertUtil.convertToString(map.get("code")))) {
					continue;
				}
				String content = "";
				if (placeEmptyFlag) {
					content = String.format(AppRemindTemplate.NewContentTemplate1, getDateStringWithWeek(scheduleEntity.getBegintime()), scheduleEntity.getName(), from);
				} else {
					if (!StringUtil.isEmpty(scheduleEntity.getTemplatetype())) {
						// 会议室申请通知做准备工作人员的消息模板，若日程的templateType非空，则使用该模板
						content = String.format(AppRemindTemplate.TemplateMap.get(scheduleEntity.getTemplatetype()), getDateStringWithWeek(scheduleEntity.getBegintime()), place, from);
					} else {
						content = String.format(AppRemindTemplate.NewContentTemplate2, getDateStringWithWeek(scheduleEntity.getBegintime()), scheduleEntity.getName(), place, from);
					}
				}
				pushList.add(createRemindTaskEntity(AppRemindTemplate.NewSubjectTemplate, content, String.valueOf(scheduleEntity.getId()), map, BaseSystemConst.BaseActionType.Create));
			}
		} else {
			// 修改状态下，比对用户
			Map<String, Object> newUserMap = processToMapUsers(newUserList);
			List<Map<String, Object>> newMapList = basePermissionManageService.getAllAttendUser(newUserMap);
			Map<String, Object> oldUserMap = processToMapUsers(oldUserList);
			List<Map<String, Object>> oldMapList = basePermissionManageService.getAllAttendUser(oldUserMap);
			// 新增的推送新增消息，修改的根据参数推送修改消息，删除的推送删除消息
			for (Map<String, Object> oldMap : oldMapList) {
				if (userCode.equals(ConvertUtil.convertToString(oldMap.get("code")))) {
					continue;
				}
				String code = ConvertUtil.convertToString(oldMap.get("code"));
				if (!newMapList.stream().anyMatch(m -> ConvertUtil.convertToString(m.get("code")).equals(code))) {
					String content = "";
					if (placeEmptyFlag) {
						content = String.format(AppRemindTemplate.DelContentTemplate1, getDateStringWithWeek(scheduleEntity.getBegintime()), scheduleEntity.getName(), from);
					} else {
						content = String.format(AppRemindTemplate.DelContentTemplate2, getDateStringWithWeek(scheduleEntity.getBegintime()), scheduleEntity.getName(), place, from);
					}
					pushList.add(createRemindTaskEntity(AppRemindTemplate.DelSubjectTemplate, content, String.valueOf(scheduleEntity.getId()), oldMap, BaseSystemConst.BaseActionType.Delete));
				}
			}
			for (Map<String, Object> newMap : newMapList) {
				if (userCode.equals(ConvertUtil.convertToString(newMap.get("code")))) {
					continue;
				}
				String code = ConvertUtil.convertToString(newMap.get("code"));
				String content = "";
				if (!oldMapList.stream().anyMatch(m -> ConvertUtil.convertToString(m.get("code")).equals(code))) {
					if (placeEmptyFlag) {
						content = String.format(AppRemindTemplate.NewContentTemplate1, getDateStringWithWeek(scheduleEntity.getBegintime()), scheduleEntity.getName(), from);
					} else {
						content = String.format(AppRemindTemplate.NewContentTemplate2, getDateStringWithWeek(scheduleEntity.getBegintime()), scheduleEntity.getName(), place, from);
					}
					pushList.add(createRemindTaskEntity(AppRemindTemplate.NewSubjectTemplate, content, String.valueOf(scheduleEntity.getId()), newMap, BaseSystemConst.BaseActionType.Create));
				} else if (isPushEdit) {
					content = String.format(AppRemindTemplate.EditContentTemplate1, getDateStringWithWeek(scheduleEntity.getBegintime()), scheduleEntity.getName(), from);
					pushList.add(createRemindTaskEntity(AppRemindTemplate.EditSubjectTemplate, content, String.valueOf(scheduleEntity.getId()), newMap, BaseSystemConst.BaseActionType.Update));
				}
			}
		}
		baseRemindTaskService.insertBatch(pushList);
	}

	/**
	 * @description:比较两个是否一致
	 * @param oldUserList
	 * @param newUserList
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月12日下午3:32:05
	 * @modify:
	 */
	private boolean comparePermissionManage(List<BasePermissionManageEntity> oldUserList, List<BasePermissionManageEntity> newUserList) {
		boolean haveChange = true;
		if (oldUserList.size() == newUserList.size()) {
			for (BasePermissionManageEntity oldPermission : oldUserList) {
				Optional<BasePermissionManageEntity> search = newUserList.stream()
						.filter(m -> m.getSharetype().equals(oldPermission.getSharetype())).findFirst();
				if (!search.isPresent()) {
					return true;
				} else {
					BasePermissionManageEntity newPermission = search.get();
					if (!newPermission.getShareobjects().equals(oldPermission.getShareobjects())) {
						return true;
					}
				}
			}
			haveChange = false;
		}
		return haveChange;
	}

	/**
	 * @description: 从OA日程到会议的日程
	 * @param inputMap
	 * @return Map
	 * @author: wangxinhua
	 * @date: 2020-11-16 10:23:06
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> syncTOAWork(Map<String, Object> inputMap) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			// 获取所有个人的日程
			List<ToaWorkingCalendarEntity> workingList = toaWorkingCalendarService
					.queryByWhere(" 1 = 1 and id = 20092800003004 ");
			// 获取所有分发日程
			List<ToaPubWorkingCalendarEntity> pubWorkingList = toaPubWorkingCalendarService.queryByWhere(" 1 = 1 ");
			// 日程实体列表
			List<BasicEntity> workScheduleEntities = new ArrayList<>();
			// 日程提醒实体列表
			List<BasicEntity> allRemainConfigEntities = new ArrayList<>();
			// 基础权限实体列表
			List<BasicEntity> basePermissionEntities = new ArrayList<>();
			for (ToaWorkingCalendarEntity workingCalendar : workingList) {
				WorkScheduleEntity workScheduleEntity = new WorkScheduleEntity();
				workScheduleEntity.setId(workingCalendar.getId());
				workScheduleEntity.setScheduletype("work");
				if (!StringUtil.isEmpty(workingCalendar.getContent())) {
					String index_str = workingCalendar.getContent();
					if (workingCalendar.getContent().indexOf("\r") > 0) {
						index_str = index_str.substring(0, index_str.indexOf("\r"));
					}
					if (index_str.length() > 47) {
						index_str = index_str.substring(0, 47) + "...";
						workScheduleEntity.setName(index_str);
					} else {
						workScheduleEntity.setName(index_str);
					}
				}
				if (!StringUtil.isEmpty(workingCalendar.getContent()) && workingCalendar.getContent().length() > 47) {
					workScheduleEntity.setName(workingCalendar.getContent().substring(0, 10) + "...");
				} else {
					workScheduleEntity.setName(workingCalendar.getContent());
				}
				workScheduleEntity.setContent(workingCalendar.getContent());
				workScheduleEntity.setBegintime(workingCalendar.getStarttime());
				workScheduleEntity.setEndtime(workingCalendar.getEndtime());
				workScheduleEntity.setHandleusercode(workingCalendar.getUsercode());
				workScheduleEntity.setHandleusername(workingCalendar.getUsername());
				workScheduleEntity.setSortCode(workingCalendar.getSortcode());
				workScheduleEntity.setEnabled(workingCalendar.getEnabled());
				workScheduleEntity.setCreateorgid(workingCalendar.getCreateorgid());
				workScheduleEntity.setCreateon(workingCalendar.getCreateon());
				workScheduleEntity.setCreateuser(workingCalendar.getCreateuser());
				workScheduleEntity.setModifiedon(workingCalendar.getModifiedon());
				workScheduleEntity.setModifieduser(workingCalendar.getModifieduser());
				// 判断是否消息提醒
				if (workingCalendar.getRemindtypecode() > 0) {
					allRemainConfigEntities.addAll(addRemainConfig(workingCalendar));
				}
				// 判断是否是从分发表发布的
				if (workingCalendar.getExtendfield2() == null) {
					workScheduleEntities.add(workScheduleEntity);
					// 不是从分发表发布的
					BasePermissionManageEntity basePermissionManageEntity = new BasePermissionManageEntity();
					long[] arrayId = PrimaryKeyUtil.GeneIDsFromCache(basePermissionManageEntity.getTableName(), 1);
					basePermissionManageEntity.setId(arrayId[0]);
					basePermissionManageEntity.setSourcetype("workSchedule");
					basePermissionManageEntity.setSourceid(String.valueOf(workingCalendar.getId()));
					basePermissionManageEntity.setSourceusernames(workingCalendar.getUsername());
					basePermissionManageEntity.setSourceusercodes(workingCalendar.getUsercode());
					basePermissionManageEntity.setSourceflag("owner");
					basePermissionManageEntity.setSharetype(ShareTypeEnum.User);
					basePermissionManageEntity.setShareobjects(workingCalendar.getUsercode());
					basePermissionManageEntity.setShareobjectsdesc(workingCalendar.getUsername());
					basePermissionManageEntity.setEnabled(1);
					basePermissionManageEntity.setCreateorgid(workingCalendar.getCreateorgid());
					basePermissionManageEntity.setCreateon(workingCalendar.getCreateon());
					basePermissionManageEntity.setCreateuser(workingCalendar.getCreateuser());
					basePermissionManageEntity.setModifiedon(workingCalendar.getModifiedon());
					basePermissionManageEntity.setModifieduser(workingCalendar.getModifieduser());
					basePermissionEntities.add(basePermissionManageEntity);
				} else {
					for (ToaPubWorkingCalendarEntity tpwc : pubWorkingList) {
						if (workingCalendar.getExtendfield2().equals(String.valueOf(tpwc.getId()))
								&& workingCalendar.getUsercode().equals(tpwc.getHandleusercode())) {
							workScheduleEntities.add(workScheduleEntity);
						}
					}
					// 从分发表发布的
					basePermissionEntities.addAll(formatPermission(workingCalendar, pubWorkingList));
				}
			}
			// this.insertBatch(workScheduleEntities);
			// baseRemindConfigService.insertBatch(allRemainConfigEntities);
			// basePermissionManageService.insertBatch(basePermissionEntities);
			System.out.println("22");
		} catch (Exception e) {
			resMap.put("success", false);
			resMap.put("msg", e.getMessage());
			return resMap;
		}
		resMap.put("success", true);
		return resMap;
	}

	/**
	 * 添加提醒消息配置方法
	 *
	 * @param workingCalendar
	 * @return
	 * @author: wangxinhua
	 */
	private List<BaseRemindConfigEntity> addRemainConfig(ToaWorkingCalendarEntity workingCalendar) {
		List<BaseRemindConfigEntity> baseRemainConfigEntities = new ArrayList<>();
		Date now = new Date();
		Date startDate = workingCalendar.getStarttime();
		Date startDate1 = getDateBefore(startDate, 1);
		Date startDate3 = getDateBefore(startDate, 3);
		Date startDate7 = getDateBefore(startDate, 7);
		for (int i = 0; i < workingCalendar.getRemindtypecode(); i++) {
			BaseRemindConfigEntity baseRemindConfigEntity = new BaseRemindConfigEntity();
			long[] arrayId = PrimaryKeyUtil.GeneIDsFromCache(baseRemindConfigEntity.getTableName(), 1);
			baseRemindConfigEntity.setId(arrayId[0]);
			baseRemindConfigEntity.setSourcetype("workSchedule");
			baseRemindConfigEntity.setSourceid(String.valueOf(workingCalendar.getId()));
			baseRemindConfigEntity.setRemindtype("1");
			baseRemindConfigEntity.setUnit("1");
			baseRemindConfigEntity.setNoticetype("app");
			baseRemindConfigEntity.setEnabled(1);
			baseRemindConfigEntity.setCreateorgid(workingCalendar.getCreateorgid());
			baseRemindConfigEntity.setCreateon(workingCalendar.getCreateon());
			baseRemindConfigEntity.setCreateuser(workingCalendar.getCreateuser());
			baseRemindConfigEntity.setModifiedon(workingCalendar.getModifiedon());
			baseRemindConfigEntity.setModifieduser(workingCalendar.getModifieduser());
			// 判断日程开始时间是否大于现在时间
			if (startDate.compareTo(now) >= 0) {
				// 需要1次提醒
				if (i == 0) {
					baseRemindConfigEntity.setValue("24");
					if (now.compareTo(startDate1) <= 0) {
						baseRemindConfigEntity.setState(0);
					} else {
						baseRemindConfigEntity.setState(1);
						baseRemindConfigEntity.setRemindtime(startDate1);
					}
				}
				// 需要2次提醒
				if (i == 1) {
					baseRemindConfigEntity.setValue("72");
					if (now.compareTo(startDate3) <= 0) {
						baseRemindConfigEntity.setState(0);
					} else {
						baseRemindConfigEntity.setState(1);
						baseRemindConfigEntity.setRemindtime(startDate3);
					}
				}
				// 需要3次提醒
				if (i == 2) {
					baseRemindConfigEntity.setValue("168");
					if (now.compareTo(startDate7) <= 0) {
						baseRemindConfigEntity.setState(0);
					} else {
						baseRemindConfigEntity.setState(1);
						baseRemindConfigEntity.setRemindtime(startDate7);
					}
				}
			} else {
				baseRemindConfigEntity.setState(1);
				if (i == 0) {
					baseRemindConfigEntity.setValue("24");
					baseRemindConfigEntity.setRemindtime(startDate1);
				}
				if (i == 1) {
					baseRemindConfigEntity.setValue("72");
					baseRemindConfigEntity.setRemindtime(startDate3);
				}
				if (i == 2) {
					baseRemindConfigEntity.setValue("168");
					baseRemindConfigEntity.setRemindtime(startDate7);
				}
			}
			baseRemainConfigEntities.add(baseRemindConfigEntity);
		}
		return baseRemainConfigEntities;
	}

	/**
	 * 添加基础权限数据
	 *
	 * @param working
	 * @param sourcePubs
	 * @return
	 * @author: wangxinhua
	 */
	private List<BasePermissionManageEntity> formatPermission(ToaWorkingCalendarEntity working, List<ToaPubWorkingCalendarEntity> sourcePubs) {
		ToaPubWorkingCalendarEntity sourcePub = new ToaPubWorkingCalendarEntity();
		for (ToaPubWorkingCalendarEntity sp : sourcePubs) {
			if (working.getExtendfield2().equals(String.valueOf(sp.getId()))) {
				sourcePub = sp;
				break;
			}
		}
		List<BasePermissionManageEntity> formatEntities = new ArrayList<BasePermissionManageEntity>();
		// 添加用户的permission
		if (!StringUtil.isEmpty(sourcePub.getUsercodes())) {
			BasePermissionManageEntity basePermissionManageEntity = new BasePermissionManageEntity();
			long[] arrayId = PrimaryKeyUtil.GeneIDsFromCache(basePermissionManageEntity.getTableName(), 1);
			basePermissionManageEntity.setId(arrayId[0]);
			basePermissionManageEntity.setSourcetype("workSchedule");
			basePermissionManageEntity.setSourceid(String.valueOf(working.getId()));
			basePermissionManageEntity.setSourceusercodes(working.getUsercode());
			basePermissionManageEntity.setSourceusernames(working.getUsername());
			basePermissionManageEntity.setSourceflag("owner");
			basePermissionManageEntity.setSharetype(BaseSystemConst.ShareTypeEnum.User);
			basePermissionManageEntity.setShareobjects(sourcePub.getUsercodes().substring(0, sourcePub.getUsercodes().length() - 1).replace(";", ","));
			basePermissionManageEntity.setShareobjectsdesc(sourcePub.getUsernames().substring(0, sourcePub.getUsernames().length() - 1).replace(";", ","));
			basePermissionManageEntity.setDescription(sourcePub.getDescription());
			basePermissionManageEntity.setEnabled(working.getEnabled());
			basePermissionManageEntity.setCreateorgid(working.getCreateorgid());
			basePermissionManageEntity.setCreateon(working.getCreateon());
			basePermissionManageEntity.setCreateuser(working.getCreateuser());
			basePermissionManageEntity.setModifiedon(working.getModifiedon());
			basePermissionManageEntity.setModifieduser(working.getModifieduser());
			formatEntities.add(basePermissionManageEntity);
		}
		// 添加部门permission
		if (!StringUtil.isEmpty(sourcePub.getSuitdeptcodes())) {
			BasePermissionManageEntity basePermissionManageEntity = new BasePermissionManageEntity();
			long[] arrayId = PrimaryKeyUtil.GeneIDsFromCache(basePermissionManageEntity.getTableName(), 1);
			basePermissionManageEntity.setId(arrayId[0]);
			basePermissionManageEntity.setSourcetype("workSchedule");
			basePermissionManageEntity.setSourceid(String.valueOf(working.getId()));
			basePermissionManageEntity.setSourceusercodes(working.getUsercode());
			basePermissionManageEntity.setSourceusernames(working.getUsername());
			basePermissionManageEntity.setSourceflag("owner");
			basePermissionManageEntity.setSharetype(ShareTypeEnum.Dept);
			basePermissionManageEntity.setShareobjects(sourcePub.getSuitdeptcodes()
					.substring(0, sourcePub.getSuitdeptcodes().length() - 1).replace(";", ","));
			basePermissionManageEntity.setShareobjectsdesc(sourcePub.getSuitdeptnames()
					.substring(0, sourcePub.getSuitdeptnames().length() - 1).replace(";", ","));
			basePermissionManageEntity.setDescription(sourcePub.getDescription());
			basePermissionManageEntity.setEnabled(working.getEnabled());
			basePermissionManageEntity.setCreateorgid(working.getCreateorgid());
			basePermissionManageEntity.setCreateon(working.getCreateon());
			basePermissionManageEntity.setCreateuser(working.getCreateuser());
			basePermissionManageEntity.setModifiedon(working.getModifiedon());
			basePermissionManageEntity.setModifieduser(working.getModifieduser());
			formatEntities.add(basePermissionManageEntity);
		}
		// 添加角色permission
		if (!StringUtil.isEmpty(sourcePub.getRoleids())) {
			BasePermissionManageEntity basePermissionManageEntity = new BasePermissionManageEntity();
			long[] arrayId = PrimaryKeyUtil.GeneIDsFromCache(basePermissionManageEntity.getTableName(), 1);
			basePermissionManageEntity.setId(arrayId[0]);
			basePermissionManageEntity.setSourcetype("workSchedule");
			basePermissionManageEntity.setSourceid(String.valueOf(working.getId()));
			basePermissionManageEntity.setSourceusercodes(working.getUsercode());
			basePermissionManageEntity.setSourceusernames(working.getUsername());
			basePermissionManageEntity.setSourceflag("owner");
			basePermissionManageEntity.setSharetype(ShareTypeEnum.Role);
			basePermissionManageEntity.setShareobjects(sourcePub.getRoleids().substring(0, sourcePub.getRoleids().length() - 1).replace(";", ","));
			basePermissionManageEntity.setShareobjectsdesc(sourcePub.getRolenames().substring(0, sourcePub.getRolenames().length() - 1).replace(";", ","));
			basePermissionManageEntity.setDescription(sourcePub.getDescription());
			basePermissionManageEntity.setEnabled(working.getEnabled());
			basePermissionManageEntity.setCreateorgid(working.getCreateorgid());
			basePermissionManageEntity.setCreateon(working.getCreateon());
			basePermissionManageEntity.setCreateuser(working.getCreateuser());
			basePermissionManageEntity.setModifiedon(working.getModifiedon());
			basePermissionManageEntity.setModifieduser(working.getModifieduser());
			formatEntities.add(basePermissionManageEntity);
		}
		return formatEntities;
	}

	/**
	 * 获取换入日期的几天前时间
	 *
	 * @param d
	 * @param day
	 * @return
	 * @author: wangxinhua
	 */
	private static Date getDateBefore(Date d, int day) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
		return now.getTime();
	}
	/**
	 * @description: 获取带有星期的时间String
	 * @author xinfushuo
	 * @param date
	 * @return	 yyyy-MM-dd E HH:mm 格式时间
	 * @date 2022/6/6
	 * @modify
	 */
	public static String getDateStringWithWeek(Date date){
		String format = "yyyy-MM-dd E HH:mm";
		SimpleDateFormat formatter;
		formatter = new SimpleDateFormat(format, Locale.CHINA);
		return formatter.format(date);
	}
}
